package com.xu.sso.web.controller;

import com.xu.sso.client.filter.LoginFilter;
import com.xu.sso.client.model.UserLoginInfo;
import com.xu.sso.core.exception.SSOException;
import com.xu.sso.core.model.BaseResponse;
import com.xu.sso.db.model.base.Department;
import com.xu.sso.db.model.base.User;
import com.xu.sso.web.model.request.UpdateUserRequest;
import com.xu.sso.web.service.ManageService;
import com.xu.sso.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ManageService manageService;

    @RequestMapping("/toUser")
    public String toUser(Model model) {
        UserLoginInfo userLoginInfo = LoginFilter.threadLocal.get();
        User user = userService.findUser(userLoginInfo.getUsername());
        model.addAttribute("user", user);
        return "user/user";
    }

    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "user/updatePwd";
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public BaseResponse updatePwd(String oldPwd, String newPwd) throws SSOException {
        UserLoginInfo userLoginInfo = LoginFilter.threadLocal.get();
        return userService.updatePwd(userLoginInfo.getUsername(), newPwd, oldPwd);
    }

    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(Model model) {
        UserLoginInfo userLoginInfo = LoginFilter.threadLocal.get();
        User user = userService.findUser(userLoginInfo.getUsername());
        List<Department> list = manageService.findAllDepartment();
        model.addAttribute("user", user);
        model.addAttribute("deps", list);
        return "user/updateUser";
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    public BaseResponse updateUser(UpdateUserRequest request) throws SSOException {
        return userService.updateUser(request);
    }

    @RequestMapping("/toAddUser")
    public String toAddUser(Model model) {
        return "user/addUser";
    }

}
